package cn.msn.user.interceptor;

import cn.msn.basic.jwt.JwtUtils;
import cn.msn.basic.jwt.LoginData;
import cn.msn.basic.jwt.Payload;
import cn.msn.basic.jwt.RsaUtils;
import cn.msn.system.annotation.PreAuthorize;
import cn.msn.system.mapper.PermissionMapper;
import cn.msn.user.domain.Logininfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;
import java.util.List;

@Component
	public class LoginInterceptor implements HandlerInterceptor {

	    @Autowired
	    private PermissionMapper permissionMapper;

	    // 在处理器【controller】执行之前执行
	    @Override
	    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
			String token = request.getHeader("token");
			if (token!=null){
				Logininfo logininfo = null;
				try {
					// 获取公钥
					PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
					// 解密
					Payload<LoginData> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginData.class);
					// 获取登录信息
					logininfo = payload.getLoginData().getLogininfo();
				} catch (Exception e) {
					response.setContentType("application/json;charset=UTF-8");
					response.getWriter().println("{\"success\":false,\"msg\":\"timeout\"}");
					return false;
				}
				//管理员 - 有权限 - 需要验证权限
				//1. 获取当前你访问接口的自定义注解的sn
				HandlerMethod method = (HandlerMethod)handler;//访问的接口方法
				//获取当前方法中的名词为PreAuthorize
				PreAuthorize preAuthorize = method.getMethodAnnotation(PreAuthorize.class);
				if(preAuthorize==null){//没有加注解不需要验证权限
					return true;
				}else{//接口上有这个PreAuthorize注解 - 验证
					//获取sn属性值
					String sn = preAuthorize.sn();
					//获取当前登录人所有权限
					List<String> myPermissions = permissionMapper.getPermissionsByLogininfoId(logininfo.getId());
					//2. 获取当前登录人的所有权限的sn
					//3.判断：包含 - 有权限 - 放行。不包含 - 没有权限 - 返回没有权限的信息
					if(myPermissions.contains(sn)){
						return true;
					}else{//没有权限去访问
						response.setContentType("application/json;charset=UTF-8");
						response.getWriter().println("{\"success\":false,\"msg\":\"noPermission\"}");
						return false;
					}
				}

			}


			response.setContentType("application/json;charset=UTF-8");
	        response.getWriter().println("{\"success\":false,\"msg\":\"noLogin\"}");
	        return false;
	    }
	}